const ble = require("../../utils/bluetooth");
const util = require("../../utils/util");
const app = getApp()

Page({ 
  data: {
    conncted : false,
    deviceListShow: false,
    btnShow : true,
    devices : [],
    gradientColor: {
      '0%': '#DEB9FF',
      '100%': '#0456FE',
    },
    checked : false,
    showPivot : false,
    battery_list : [["01","02"],["03","04"],["01","02"],["01","02"],["01","02"],["01","02"],["01","02"],["01","02"],["01","02"],["01","02"],["01","02"],["01","11"]],
    hidden_last : true,
    warn_list : [],
    timer : null,
    timer2 : null,
    sn : "",
    pack: "",
    battery_type : "",
    full: "",
    remain:"",
    precent: "",
    progress: 0,
    chongdian_state : false,
    fangdian_state : false,
    chongdian_mos : false,
    fangdian_mos : false,
    junheng_state : false,
    total : 0,
    electri : 0,
    power : 0,
    loop : 0,
    chongdian_counter: "",
    chongdian_total: "",
    max : 0,
    min : 0,
    avg: 0,
    diff: 0,
    largestThree : [],
    smallestThree : [],
    mos_t : 0,
    huanjing_t : 0,
    t1 : 0,
    t2 : 0,
    t3 : 0,
    t4 : 0,
    t5 : 0,
    shendu_color : "#129123",
    shendu_progress : 0,
    protect_text : "",
    playing_1 : false,
    playing_2 : false,
    playing_3 : false,
    playing_4 : false,
    playing_5 : false,
    playing_6 : false,
    playing_7 : false,
    warn_sound_count_1 : 0,
    warn_sound_count_2 : 0,
    warn_sound_count_3 : 0,
    warn_sound_count_4 : 0,
    warn_sound_count_5 : 0,
    warn_sound_count_6 : 0,
    warn_sound_count_7 : 0,
    total_diff : ""
  },
 
  onLoad() {
    ble.setApp(app)
  },

  onShow() {
    if (!this.data.conncted) {
      return
    }

    this.stopTimer2()
    this.loopReadData()
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.stopTimer()
    this.loopReadData2()
  },

  stopTimer2(){
    if (this.data.timer2 != null) {
      clearInterval(this.data.timer2)
      this.data.timer2 = null
    }
  },

  stopTimer(){
    if (this.data.timer != null) {
      clearInterval(this.data.timer)
      this.data.timer = null
    }
  },

  disconnect(e) {
    ble.disconnect()
    this.stopTimer()
    this.stopTimer2()
    wx.showToast({
      title: '蓝牙已断开连接',
      icon: 'none'
    })
  },

  initBluetooth(e) {
    const that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting.hasOwnProperty('scope.bluetooth')) {
          //'scope.bluetooth'属性存在，且为false
          if (!res.authSetting['scope.bluetooth']) {
            wx.showModal({
              title: '温馨提示',
              showCancel: false,
              content: '获取蓝牙授权失败，需要手动授权'
            })
          } else {
            that.checkPrivacyAuthorize(e);
          }
        } else {
          //'scope.bluetooth'属性不存在，需要授权
          that.checkPrivacyAuthorize(e);
        }
      }
    })
  },

  checkPrivacyAuthorize(e) {
    // this.initBluetooth()
    const that = this;
    const type = e.currentTarget.dataset.type;
    if (wx.requirePrivacyAuthorize) {
      wx.requirePrivacyAuthorize({
        success: res => {
          if (type == 1) {
            that.scanDevices()
          } else {
            that.scanQRCode()
          }
        },
        fail: res => {
          console.log('用户拒绝了隐私协议')
        }
      })
    } else {
      if (type == 1) {
        that.scanDevices()
      } else {
        that.scanQRCode()
      }
    }
  },

  scanDevices() {
    const that = this
    that.setData({
      deviceListShow : true
    })
 
    ble.initialize("NB", function(res){}, null, function(res){
      that.setData({
        devices : res
      })
    });
  },

  scanQRCode() {
    let that = this;
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success (res) {
        console.log(res.result)
        ble.initialize(res.result, function(res){
          console.log("connect success")
          that.loopReadData()
        }, null, null);
      }
    })
  },

  stopTz(){
    console.log("hah")
  },

  closeDialog() {
    console.log("close")
    ble.clearBluetooth()
    this.setData({
      devices: []
    })
  },

  selectDevice(e){
    const that = this
    that.setData({
      deviceListShow : false
    })
    wx.showLoading()
    const deviceid = e.currentTarget.dataset.deviceid;
    ble.connectBluetooth(deviceid, function(res){
      ble.clearBluetooth()
      that.setData({
        devices : [],
        conncted : true,
        sn : "",
        pack : ""
      })
      wx.hideLoading()
      that.loopReadData()
    })
  },

  loopReadData() {
    if (ble.isConncted()) {
      this.stopTimer()
      this.data.timer = setInterval(async () => {
        await this.readBLE();
      }, 2000) 
    }
  },

  loopReadData2() {
    if (ble.isConncted()) {
      this.stopTimer2()
      this.data.timer2 = setInterval(async () => {
        await ble.getDesingerCap(true)
      }, 5000) 
    }
  },

  async readBLE(){
    let sn = this.data.sn
    // if (sn.length < 10) {
    sn = await ble.getSN()
    // }

    let pack = this.data.pack
    // if (pack.length < 5) {
    pack = await ble.getPack()
    // }
    app.globalData.battery.model = pack

    let ov_port = await ble.getOVPROT()
    let battery_type = this.getType(ov_port)

    let designers = await ble.getDesingerCap(false)
    let designerCap = designers[0]
    app.globalData.battery.design = designerCap
    app.globalData.battery.resnse = designers[2]
    let limit = designers[3]
    // console.log("阈值", limit)

    let full_list = await ble.getFull()
    // // console.log(full_list)
    app.globalData.battery.full = full_list[1]
    app.globalData.battery.shouming = full_list[11]
    app.globalData.battery.fangdian_total = full_list[12]
    let junheng = parseInt(full_list[13]) == 0 ? false : true
    let t_diff = (full_list[10] - full_list[12]).toFixed(2)
    // console.log("当前电流", full_list[8])

    let info = await ble.getBSystemInfo()
    
    // // console.log(info)

    let voltages = await ble.getEveryVoltage()

    app.globalData.battery.bnums = voltages.length
    let result = this.formatVoltages(voltages)
    // // console.log("-----------------")
    // // console.log(result)

    let temperatures = await ble.getTemperature()

    let shendu_progress = (full_list[8] * 0.1 / designerCap).toFixed(1)
    let shendu_color = this.getShenduApperence(shendu_progress)
    let warn_info = await ble.getProtectInfo()
    let l2_protect_valotage_up_100 = await ble.getAFEParams2() + 100
    let tempature_protect = await ble.getTemptureProtectParams()

    this.setData({
      sn : sn,
      pack : pack,
      battery_type : battery_type,
      precent : full_list[0],
      full : full_list[1],
      remain : full_list[2],
      progress : full_list[3],
      total : full_list[4],
      electri : full_list[5],
      power : full_list[6],
      loop : full_list[7],
      chongdian_counter : full_list[9],
      chongdian_total : full_list[10],
      chongdian_mos : info[0],
      fangdian_mos : info[1],
      chongdian_state : info[2],
      fangdian_state : info[3],
      junheng_state : junheng,
      max : result[0],
      min : result[1],
      avg : result[2],
      diff : result[3],
      battery_list : result[4],
      mos_t : temperatures[0],
      huanjing_t : temperatures[1],
      t1 : temperatures[2],
      t2 : temperatures[3],
      t3 : temperatures[4],
      t4 : temperatures[5],
      t5 : temperatures[6],
      protect_text : warn_info[0],
      warn_list : warn_info[1],
      total_diff : t_diff,
    })

    if (info[2] && shendu_progress > 0.1) {
      this.setData({
        shendu_progress : shendu_progress,
        shendu_color : shendu_color,
      })
    }

    if (info[2]) {
      this.setData({
        largestThree : result[5],
      })
    } 

    if (info[3]) {
      this.setData({
        smallestThree : result[6],
      })
    }

    if (!info[2]) {
      let ll = parseInt(result[1])
      let hh = parseInt(limit + 500)
      if (ll <= hh && this.data.warn_sound_count_1 < 3) {
        const info = "当前值:" + ll + " 目标值:" + hh + " sound_count:" + this.data.warn_sound_count_1
        this.playWarningSound("/images/warn.mp3", info, 1)
      }

      if (ll > hh) {
        this.data.warn_sound_count_1 = 0
        this.data.playing_1 = false
      }
    } else {
      this.data.warn_sound_count_1 = 0
      this.data.playing_1 = false
    }

    let gonglv_temp_protect = tempature_protect[0] - 5
    let huanjing_temp_protect = tempature_protect[1] - 5
    let chongdian_temp_protect = tempature_protect[2] - 5
    let fangdian_temp_protect = tempature_protect[3] - 5

    if (this.data.mos_t > gonglv_temp_protect) {
      if (this.data.warn_sound_count_2 < 3) {
        this.playWarningSound("/images/temp_warning.mp3", "功率温度保护告警", 2)
      }
    } else {
      this.data.warn_sound_count_2 = 0
      this.data.playing_2 = false
    }

    if (this.data.huanjing_t > huanjing_temp_protect) {
      if (this.data.warn_sound_count_3 < 3) {
        this.playWarningSound("/images/temp_warning.mp3", "环境温度保护告警", 3)
      }
    } else {
      this.data.warn_sound_count_3 = 0
      this.data.playing_3 = false
    }

    if (info[2]) {
      if (this.data.t1 > chongdian_temp_protect || this.data.t2 > chongdian_temp_protect) {
        if (this.data.warn_sound_count_4 < 3) {
          this.playWarningSound("/images/temp_warning.mp3", "T1或者T2大于充电过温保护告警", 4)
        }
      } else {
        this.data.warn_sound_count_4 = 0
        this.data.playing_4 = false
      }
    }

    if (info[3]) {
      if (this.data.t1 > fangdian_temp_protect || this.data.t2 > fangdian_temp_protect) {
        if (this.data.warn_sound_count_5 < 3) {
          this.playWarningSound("/images/temp_warning.mp3", "T1或者T2大于放电过温保护告警", 5)
        }
      } else {
        this.data.warn_sound_count_5 = 0
        this.data.playing_5 = false
      }
    }

    if (warn_info[2]) {
      if (this.data.warn_sound_count_6 < 3) {
        this.playWarningSound("/images/level2.mp3", "MOS管路损坏告警", 6)
      }
    } else {
      this.data.warn_sound_count_6 = 0
      this.data.playing_6 = false
    }

    let max_v = parseInt(result[0])
    if (max_v > l2_protect_valotage_up_100) {
      if (this.data.warn_sound_count_7 < 3) {
        this.playWarningSound("/images/level2.mp3", "最高电压超过二级过充保护电压100mv告警", 7)
      }
    } else {
      this.data.warn_sound_count_7 = 0
      this.data.playing_7 = false
    }
  },

  formatVoltages(voltages) {
    var max = 0
    var max_index = 0
    var min = 10000000000
    var min_index = 0
    var diff = 0
    var sum = 0
    const array1 = []
    var order = 1

    for (let i = 0; i < voltages.length; i++) {
      const v = voltages[i]
      array1.push({
        order : order.toString().padStart(2, "0"),
        value : v,
        level : 0,
        show : (v * 0.1).toFixed(1),
        image : "/images/battery_1.png"
      })

      order++;

      if (v > max) {
        max = v 
        max_index = i
      }

      if (v < min) {
        min = v 
        min_index = i
      }

      sum += v
    }

    array1[max_index].level = 1
    array1[max_index].image = "/images/battery_5.png"
    array1[min_index].level = -1
    array1[min_index].image = "/images/battery_2.png"

    var avg = parseInt(sum / voltages.length)
    diff = max - min

    const array2 = []
    
    for (let i = 0; i < array1.length; i+=2) {
      var o1 = array1[i]
      var o2 = {}

      if ((i+1) >= array1.length) {
        o2 = {
          value : 0,
          level : -3
        }
      } else {
        o2 = array1[i+1]
      }
      
      array2.push([o1, o2])
    }

    const result = util.findTopAndBottomThree(voltages);
    max = (max * 0.1).toFixed(1)
    min = (min * 0.1).toFixed(1)
    avg = (avg * 0.1).toFixed(1)
    diff = (diff * 0.1).toFixed(1)

    return [max, min, avg, diff, array2, result.largestThree, result.smallestThree]
  },

  getShenduApperence(r) {
    var color = ""
    // 按1C-0.11C红   0.10C-0.051C黄  0.050C-0.041C浅绿  0.040C-0.031C中绿  小于0.03C深绿  四档颜色分别是 红  黄 浅绿  中绿   深绿
    if (r >= 11 && r <= 100) {
      color = "#EF265F"
    } else if (r >= 5 && r < 11) {
      color = "#F6BE24"
    } else if (r >= 4 && r < 5) {
      color = "#D1D9F8"
    } else if (r >= 3 && r < 4) {
      color = "#218d2f"
    } else {
      color = "#129123"
    }

    return color
  },

  playWarningSound(src, info, type) {
    let that = this

    if (type == 1 && that.data.playing_1) {
      return
    }
    if (type == 2 && that.data.playing_2) {
      return
    }
    if (type == 3 && that.data.playing_3) {
      return
    }
    if (type == 4 && that.data.playing_4) {
      return
    }
    if (type == 5 && that.data.playing_5) {
      return
    }
    if (type == 6 && that.data.playing_6) {
      return
    }
    if (type == 7 && that.data.playing_7) {
      return
    }

    app.writeLog(info)
    if (type == 1) {
      that.data.playing_1 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_1 + 1
    }
    if (type == 2) {
      that.data.playing_2 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_2 + 1
    }
    if (type == 3) {
      that.data.playing_3 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_3 + 1
    }
    if (type == 4) {
      that.data.playing_4 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_4 + 1
    }
    if (type == 5) {
      that.data.playing_5 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_5 + 1
    }
    if (type == 6) {
      that.data.playing_6 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_6 + 1
    }
    if (type == 7) {
      that.data.playing_7 = true
      that.data.warn_sound_count_1 = that.data.warn_sound_count_7 + 1
    }

    console.log("开始播放")

    const innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: true 
    })
    
    // innerAudioContext.onEnded(() => {
    //   that.data.playing = false
    // })
    innerAudioContext.onPlay(() => {  
    })
    // innerAudioContext.onError(()=>{
    //   that.data.playing = false
    // })
    innerAudioContext.src = src
    innerAudioContext.play() // 播放
    setTimeout(() => {
      if (type == 1) {
        that.data.playing_1 = false
      } else if (type == 2) {
        that.data.playing_2 = false
      } else if (type == 3) {
        that.data.playing_3 = false
      } else if (type == 4) {
        that.data.playing_4 = false
      } else if (type == 5) {
        that.data.playing_5 = false
      } else if (type == 6) {
        that.data.playing_6 = false
      } else if (type == 7) {
        that.data.playing_7 = false
      }
      
    }, 30 * 1000)

  },

  getType(value) {
    var type = value
    
    // console.log("------------------------", value)
    if (value >= 2700 && value <= 2800) {
      type = "钛酸锂电池"
    } else if (value >= 3600 && value <= 3870) {
      type = "铁锂电池"
    } else if (value >= 3900 && value <= 4100) {
      type = "钠电电池"
    } else if (value >= 4130 && value <= 4350) {
      type = "三元电池"
    }

    return type
  },

  onChange({ detail }) {
    // this.setData({ checked: detail });
  },
})
